<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="部署时间">
        <el-date-picker
          v-model="daterangeDeployTime"
          style="width: 340px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="审核类型" prop="bpmnType">
        <el-select
          v-model="queryParams.bpmnType"
          placeholder="请选择审核类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_audit_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleDefine"
          v-hasPermi="['workflow:bpmnInfo:add']"
          >新建流程文件</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['workflow:bpmnInfo:deploy']"
          >流程文件部署</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bpmnInfoList">
      <el-table-column label="审核类型" align="center" prop="bpmnLabel" />
      <el-table-column
        label="流程定义Key"
        align="center"
        prop="processDefineKey"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="流程部署ID" align="center" prop="deploymentId"/>
      <el-table-column label="版本号" align="center" prop="version" />
      <el-table-column label="描述信息" align="center" prop="info" :show-overflow-tooltip="true"/>
      <el-table-column
        label="部署时间"
        align="center"
        prop="deployTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deployTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="流程文件"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleReadResource(scope.row,'file')"
            v-hasPermi="['workflow:bpmnInfo:readResource']"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        label="流程图"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleReadResource(scope.row,'img')"
            v-hasPermi="['workflow:bpmnInfo:readResource']"
            >查看</el-button
          >
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-user"
            @click="handleTask(scope.row)"
            >节点</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['workflow:bpmnInfo:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看流程文件对话框 -->
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewOpen"
      width="1200px"
      append-to-body
    >
       <prism-editor-view :code="viewData" v-if="viewFile"/>
       <div v-html="viewData" v-else></div>
    </el-dialog>

    <!-- 新建流程文件对话框 -->
    <el-dialog
      :title="defineTitle"
      :visible.sync="defineOpen"
      width="1200px"
      append-to-body
    >
      <div style="height: 450px; overflow: auto">
        <vue-bpmn product="activiti" />
      </div>
    </el-dialog>

    <!-- 部署流程定义对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="审核类型" prop="bpmnType">
          <el-select
            v-model="form.bpmnType"
            placeholder="请选择审核类型"
            clearable
          >
            <el-option
              v-for="dict in dict.type.sys_audit_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请选择文件" prop="bpmnFile">
          <el-upload
            class="upload"
            ref="upload"
            action="none"
            :auto-upload="false"
            :file-list="fileList"
            :on-change="handleChange"
            :http-request="uploadFile"
            multiple
          >
            <el-button type="success">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传文件格式: 必选[bpmn/xml/zip] 可选[svg]
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="info">
          <el-input
            type="textarea"
            :rows="5"
            v-model="form.info"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import VueBpmn from "@/components/bpmn/VueBpmn.vue";
import PrismEditorView from '@/components/prismEditorView';
import { listBpmnInfo,deploy,delBpmnInfo,readResource } from "@/api/workflow/bpmnInfo";


export default {
  name: "BpmnInfo",
  dicts: ["sys_audit_type"],
  components: {
    VueBpmn,PrismEditorView
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用,支持多个
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      bpmnInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 流程定义弹出层标题
      defineTitle: "",
      // 是否显示流程定义弹出层
      defineOpen: false,
      // 流程文件弹出层标题
      viewTitle:"",
      // 是否显示流程文件弹出层
      viewOpen: false,
      // 描述信息时间范围
      daterangeDeployTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bpmnType: null,
        deployTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bpmnType: [
          { required: true, message: "请选择审核类型", trigger: "blur" },
        ],
        info: [{ required: true, message: "备注不能为空", trigger: "blur" }],
      },
      //上传的文件列表
      fileList: [],
      //查看的是流程文件还是图
      viewFile: true,
      //查看流程文件/图
      viewData:"",
      //文件上传支持的类型
      suffixArr:['bpmn','xml','zip']
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 文件选择后执行的方法 */
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    /** 自定义上传文件的方法 */
    uploadFile() {
      console.log("自定义上传文件的方法");
    },

    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDeployTime && "" != this.daterangeDeployTime) {
        this.queryParams.params["beginDeployTime"] = this.daterangeDeployTime[0];
        this.queryParams.params["endDeployTime"] = this.daterangeDeployTime[1];
      }
      
      listBpmnInfo(this.queryParams).then((response) => {
        this.bpmnInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bpmnLabel: null,
        bpmnType: null,
        version: null,
        info: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDeployTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "部署流程定义";
    },
    /** 流程定义对话框 */
    handleDefine() {
      this.defineOpen = true;
      this.defineTitle = "新建流程定义";
    },

    /** 提交按钮 */
    submitForm() {
      // console.log("upload:",this.fileList[0].raw);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.fileList.length <= 0) {
            this.$modal.msgError("请选择要部署的流程文件");
            return;
          }
          //表单校验通过，部署流程文件
          let formData = new FormData();
          //标记有上传部署文件
          let hasDeployementFile = false;
          //对流程文件进行封装
          this.fileList.forEach(item=>{
            formData.append("fileList",item.raw);
            //判断流程部署至少要上传流程文件，图片是可选
            let filename = item.name;
            let suffix = filename.match(/[^.]+$/);
            if(this.suffixArr.includes(suffix[0])){
              //bug:当正常上传bpmn和svg,也会说要选择，所以，该判断有误
              //原因：当上传bpmn和svg时，bpmn没问题，而svg则表示没有上传。多了次判断造成的
              hasDeployementFile = true;
            }
          });
          //在循环外在判断有没有上传不是文件,没有则警告
          if(!hasDeployementFile){
            this.$modal.msgError("请选择要部署的流程文件");
            return;
          }

          formData.append("bpmnType", this.form.bpmnType);
          formData.append("info", this.form.info);
          let _this = this;
          let curObj = _this.dict.type.sys_audit_type.find(item=>{
            return item.value == _this.form.bpmnType;
          });
          formData.append("bpmnLabel", curObj.label);

          deploy(formData).then((response) => {
            //刷新表格
            this.resetQuery();
            //清空fileList数据
            this.fileList = [];
            //关闭弹窗
            this.open = false;
            //提示部署成功
            this.$modal.msgSuccess("流程部署成功");
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const bpmnInfoId = row.id;
      const deploymentId = row.deploymentId;
      this.$modal.confirm('是否确认删除流程部署的ID为"' + deploymentId + '"的数据项？').then(function() {
        return delBpmnInfo(bpmnInfoId,deploymentId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 查看流程文件/图 */
    handleReadResource(row,fileType){
      this.viewData = "";
      readResource(row.deploymentId,fileType).then(res=>{
        this.viewData = res;
        // 流程文件弹出层标题
        if(fileType == 'file'){
          this.viewTitle = "流程文件xml";
          this.viewFile = true;
        }else{
          this.viewTitle = "流程图";
          this.viewFile = false;
        }
        // 是否显示流程文件弹出层
        this.viewOpen = true
      });
    },
    /** 跳转到流程列表 */
    handleTask(row){
      //注意：无需在router.js中配置，因为会通过layout动态加载菜单管理中我们配置的路由配置到router.js中
      this.$router.push({path:'/workflow/bpmnNode',query:{id:row.id}})
    }
  },
};
</script>
